package com.hspedu.reflection;

import java.lang.reflect.Field;

/**
 * 反射操作属性
 */
public class ReflectionAccessProperty {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        Class<?> stuClass = Class.forName("com.hspedu.reflection.Stu");

        Object o = stuClass.newInstance();
        System.out.println(o.getClass());

        Field age = stuClass.getField("age");
        age.set(o,28);
        System.out.println(o);

        Field name = stuClass.getDeclaredField("name");
        name.setAccessible(true);
//        name.set(o,"小明");
        name.set(null,"小明"); //name 是 static 属性
        System.out.println(o);
    }
}

class Stu {
    private static String name;
    public int age;

    public Stu() {
    }

    @Override
    public String toString() {
        return "Stu{" +
                "name=" + name +
                ", age=" + age +
                '}';
    }
}
